package com.kfm.dingtalk.service.impl;

import cn.hutool.json.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.kfm.dingtalk.service.DingTalkService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.tomcat.Jar;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class DingTalkServiceImpl implements DingTalkService {

    @Value("${chat.webhook}")
    private String webhook;

    @Resource
    private RestTemplate restTemplate;
    @Override
    public void sendMessage(String message) throws IOException {
        Map<String, Object> payload = new HashMap<>();
        payload.put("msgtype", "text");

        Map<String, String> text = new HashMap<>();
        text.put("content", message);
        payload.put("text", text);

        RequestBody requestBody = null;
        try {
            requestBody = RequestBody.create(
                    MediaType.parse("application/json; charset=utf-8"),
                    new JsonMapper().writeValueAsString(payload));
        } catch (JsonProcessingException e) {
            log.error("JsonProcessingException", e);
            throw new RuntimeException(e);
        }
        // 发送请求
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(webhook, payload, String.class);
        log.info("stringResponseEntity: {}", stringResponseEntity);
        String responseBody = stringResponseEntity.getBody(); // 获取响应体
        HttpStatusCode code = stringResponseEntity.getStatusCode();// 获取HTTP状态码
        if (code.is2xxSuccessful()) {
            // 2xx系列状态码表示成功
            System.out.println("请求成功，响应体：" + responseBody);
        } else {
            // 非2xx系列状态码表示失败
            System.out.println("请求失败，HTTP状态码：" + code + "，响应体：" + responseBody);
        }
    }
}
